#!/usr/bin/perl
# Copyright (C) 2011-2013 Zentyal S.L.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# Import PDC Server configuration from a YAML file

use warnings;
use strict;

use EBox;
use EBox::Global;
use EBox::Sudo;
use Error qw(:try);
use YAML::XS;

if (@ARGV ne 1) {
    print "Usage: $0 <pdc.yaml>\n";
    exit 1;
}

EBox::init();

if (not EBox::Global->modExists('samba')) {
    print "zentyal-samba module is not installed. Aborting\n";
    exit 1;
}

# Import configuration file
my ($pdc_data) = YAML::XS::LoadFile($ARGV[0]);
my $domain = $pdc_data->{domain};
my $servername = $pdc_data->{servername};
my $domainSid = $pdc_data->{sid};
my $computers = $pdc_data->{computers};

my $samba = EBox::Global->modInstance('samba');
my $general = $samba->model('GeneralSettings');
$general->set(pdc => 1,
              workgroup => $domain,
              netbios => $servername,
              drive => 'H:',
              sambaGroup => 1901);
$samba->saveConfig();

my @cmds;

push (@cmds, 'invoke-rc.d zentyal samba restart');

foreach my $name (keys %{$computers}) {
    my $sid = $computers->{$name};
    push (@cmds, "smbldap-useradd -W $name");
    push (@cmds, "pdbedit -r $name -U $sid");
}

push (@cmds, 'rm -f /var/lib/samba/*.tdb');
push (@cmds, "/usr/share/zentyal-samba/fix-sid $domainSid");
push (@cmds, 'invoke-rc.d zentyal samba restart');

EBox::Sudo::root(@cmds);
